package com.jia.leetCode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @program: Leetcode
 * @description:  https://leetcode-cn.com/problems/permutations-ii/submissions/
 * @author: STU756
 * @create: 2020-09-01 16:28
 */
public class Pro0047 {
    Set<List<Integer>> set = new HashSet<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        dfs(nums, 0);
        List<List<Integer>> ans = new ArrayList<>(set);
        return ans;
    }
    private void dfs(int[] nums, int cur) {
        if(cur == nums.length) {
            List<Integer> line = new ArrayList<>();
            for(int i : nums) {
                line.add(i);
            }
            set.add(line);
            return;
        }
        for(int i = cur; i < nums.length; i++) {
            if(canSwap(nums, cur, i)) {
                swap(nums, cur, i);
                dfs(nums, cur + 1);
                swap(nums, cur, i);
            }
        }
    }
    private boolean canSwap(int[] nums, int st, int ed) {
        for(int i = st; i < ed; i++) {
            if(nums[i] == nums[ed]) {
                return false;
            }
        }
        return true;
    }
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
